use yew::prelude::*;
use yew_router::prelude::*;

use crate::{hooks::use_crates, Route};

#[derive(Properties, PartialEq)]
pub struct Props {
  pub token: AttrValue,
}

#[function_component]
pub fn CrateList(props: &Props) -> HtmlResult {
  let crates = use_crates(&props.token.clone())?;

  Ok(html! {
    <>
      <p>
        <Link<Route> to={Route::CratesAdd}>
          {"+ Add new crates"}
        </Link<Route>>
      </p>
      <table>
        <thead>
          <th>{"ID"}</th>
          <th>{"Name"}</th>
          <th>{"Code"}</th>
          <th>{"Rustacean ID"}</th>
          <th>{"Version"}</th>
          <th>{"Description"}</th>
          <th>{"Crate At"}</th>
          <th>{"Operations"}</th>
        </thead>
        <tbody>
        {
          crates.into_iter().map(|crates_c| {
            html! {
              <tr>
                <td>{crates_c.id}</td>
                <td>{crates_c.name}</td>
                <td>{crates_c.code}</td>
                <td>{crates_c.rustacean_id}</td>
                <td>{crates_c.version}</td>
                <td>{crates_c.description}</td>
                <td>{crates_c.created_at}</td>
                <td>
                  <Link<Route> to={Route::CratesEdit { id: crates_c.id }}>
                    {"edit"}
                  </Link<Route>>
                  {" | "}
                  <Link<Route> to={Route::CratesDelete { id: crates_c.id }}>
                    {"delete"}
                  </Link<Route>>
                </td>
              </tr>
            }
          }).collect::<Html>()
        }
        </tbody>
      </table>
    </>
  })
}
